package org.real.guetshop.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.real.guetshop.propertis.JwtProperties;
import org.real.guetshop.context.BaseContext;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.real.guetshop.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    //TODO 后期修改
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            DecodedJWT decodedJWT = JwtUtil.verifyToken(token); // 假设 JwtUtil.verifyToken 使用 DecodedJWT 类型
            Integer empId = Integer.valueOf(decodedJWT.getSubject());
            log.info("当前员工id：{}", empId);
            BaseContext.setCurrentId(empId);
            // 3、通过，放行
            return true;
        } catch (JWTVerificationException e) { // 捕获 JWT 验证异常
            log.error("Token验证失败: {}", e.getMessage());
            // 4、不通过，响应401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token验证失败");
            return false;
        } catch (Exception e) {
            // 其他异常处理
            log.error("Token处理异常: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("服务器内部错误");
            return false;
        }
    }
}
